/**
 * Copyright 2021 xieyuanhui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.milantiejiang.tuto;

import android.content.Context;
import android.util.Log;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

public class SendMsgImpl implements ISendMsg {
    private final String TAG = SendMsgImpl.class.getSimpleName();

    @Override
    public int sendMsg(Context context, String msg) {
        ClientThread runnable = new ClientThread();
        runnable.setRspListener((IRspListener) context);
        byte[] msgBytes = msg.getBytes();
        byte[] sendStr = Utils.buildMsg(Utils.int2Bytes_LE(msgBytes.length), msgBytes);
        runnable.setmMsg(sendStr);
        new Thread(runnable).start();
        return 0;
    }

    @Override
    public int sendFile(Context context, String filePath) {
        ClientThread runnable = new ClientThread();
        runnable.setRspListener(new IRspListener() {
            private ReentrantLock mLock = new ReentrantLock(true);

            @Override
            public void onTimeOut() {

            }

            @Override
            public void onRspMsg(Socket sockets, String msg) {
                if (msg.equals(CommContent.SEND_FILE)) {
                    mLock.lock();
                    try {
                        Socket socket = null;
                        try {
                            socket = new Socket(CommContent.IP, CommContent.PORT);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        InputStream input = null;
                        DataOutputStream doutput = null;
                        OutputStream output = null;
                        DataInputStream dinput = null;
                        try {
                            socket.setSoTimeout(5 * 60 * 1000);
                            output = socket.getOutputStream();
                            doutput = new DataOutputStream(output);
                            File file = new File(filePath);
                            DataInputStream fileInputStream = new DataInputStream(new FileInputStream(file));
                            byte[] buf = new byte[1024];
                            int len = 0;
                            Log.i(TAG, Thread.currentThread().getName() + " 向服务端发送文件");
                            while ((len = fileInputStream.read(buf)) != -1) {
                                doutput.write(buf, 0, len);
                            }
                            Log.i(TAG, "文件传输完成！！");
                            doutput.flush();
                            fileInputStream.close();
                        } catch (SocketTimeoutException e) {
                            Log.i(TAG, "连接超时");
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if (input != null) {
                                    input.close();
                                }
                                if (dinput != null) {
                                    dinput.close();
                                }
                                if (output != null) {
                                    output.close();
                                }
                                if (doutput != null) {
                                    doutput.close();
                                }
                                Log.i(TAG, "Stream close");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } finally {
                        mLock.unlock();
                    }
                }
            }
        });
        byte[] msgBytes = CommContent.SEND_FILE.getBytes();
        byte[] sendStr = Utils.buildMsg(Utils.int2Bytes_LE(msgBytes.length), msgBytes);
        runnable.setmMsg(sendStr);
        new Thread(runnable).start();
        return 0;
    }

    @Override
    public int reqDowloadFile(Context context) {
        ClientThread runnable = new ClientThread();
        runnable.setRspListener(new IRspListener() {
            @Override
            public void onTimeOut() {

            }

            @Override
            public void onRspMsg(Socket socket, String msg) {
                if (msg.equals(CommContent.DOWLOAD_FILE)) {
                    //处理文件接收任务
                    Log.i(TAG, "接收服务端的文件");
                    InputStream input = null;//来自客户端的数据
                    DataInputStream dinput = null;
                    OutputStream output = null;//发送给客户端的数据
                    DataOutputStream doutput = null;
                    try {
                        input = socket.getInputStream();
                        dinput=new DataInputStream(input);

                        Date date=new Date();
                        DataOutputStream fileDataOutputStream=new DataOutputStream(new FileOutputStream(MainActivity.path+"receverServiceFile"+date.getTime()+".txt"));
                        byte[] buf=new byte[1024];
                        int len=0;
                        while ((len=dinput.read(buf))!=-1){
                            fileDataOutputStream.write(buf,0,len);
                            Log.i(TAG, "写入文件... "+len);
                        }
                        Log.i(TAG, "文件下载完成！！");
                        fileDataOutputStream.flush();
                        fileDataOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            if(input!=null){
                                input.close();
                            }
                            if(dinput!=null){
                                dinput.close();
                            }
                            if(output!=null){
                                output.close();
                            }
                            if(doutput!=null){
                                doutput.close();
                            }
                            Log.i(TAG, "Stream close");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        byte[] msgBytes = CommContent.DOWLOAD_FILE.getBytes();
        byte[] sendStr = Utils.buildMsg(Utils.int2Bytes_LE(msgBytes.length), msgBytes);
        runnable.setmMsg(sendStr);
        new Thread(runnable).start();
        return 0;
    }
}
